﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using BitcoinMarket.Resources;
using BitcoinMarket.DataConnectors;
using System.Collections.ObjectModel;
using Telerik.Windows.Controls;
using BitcoinMarket.Libs;
using Telerik.Charting;
using Microsoft.Phone.Shell;
using System.ComponentModel;
using System.Windows.Controls.Primitives;
using System.Threading;

namespace BitcoinMarket
{
    public partial class MainPage : PhoneApplicationPage
    {
        //BackgroundWorker backroungWorker;
        //Popup myPopup;

        // Constructor
        public MainPage()
        {
            App.MainPageObj = this;

            InitializeComponent();

            //Check internet connection
            if (Microsoft.Phone.Net.NetworkInformation.NetworkInterface.NetworkInterfaceType == Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.None)
            {
                MessageBox.Show(AppResources.NoDataConnectionMsg, AppResources.NoDataConnection, MessageBoxButton.OK);
            }

            //Temporary remove the "%" sign where the date of the Currency list will be shown after the data is loaded
            LabelAvgPriceOneBtc.Text = AppResources.PriceOneBitcoin.Replace("(%s)", "");
            
            //myPopup = new Popup() { IsOpen = true, Child = new AnimatedSplashScreen() };
            //backroungWorker = new BackgroundWorker();
            //this.RunBackgroundWorker();

            // Set the data context of the listbox control to the sample data
            DataContext = App.ViewModel;
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
        }

        /// <summary>
        /// Background worker for the animaed splash screen
        /// </summary>
        /*private void RunBackgroundWorker()
        {
            backroungWorker.DoWork += ((s, args) =>
            {
                //Check internet connection
                if (Microsoft.Phone.Net.NetworkInformation.NetworkInterface.NetworkInterfaceType == Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.None)
                {
                    this.Dispatcher.BeginInvoke(() =>
                        {
                          //  MessageBox.Show(AppResources.NoDataConnectionMsg, AppResources.NoDataConnection, MessageBoxButton.OK);
                        });
                }

                //Write the current date to the Currency list
                //TODO show the last modified date of the data source file if the data is not actual
                 this.Dispatcher.BeginInvoke(() =>
                    {
                        //LabelAvgPriceOneBtc.Text = AppResources.PriceOneBitcoin.Replace("%s", DateTime.Today.ToShortDateString());
                    });
            });

            backroungWorker.RunWorkerCompleted += ((s, args) =>
            {
               /* this.Dispatcher.BeginInvoke(() =>
                    {
                        this.myPopup.IsOpen = false;
                    });*
            });
            backroungWorker.RunWorkerAsync();
        }*/
        // Load data for the ViewModel Items
        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            SystemTray.IsVisible = true;
            SystemTray.Opacity = 0;
            SystemTray.ForegroundColor = ColorTools.GetColorFromHexa("#FF4D4D4D");

            this.BuildLocalizedApplicationBar();

            if (!App.ViewModel.IsDataLoaded)
            {
                App.ViewModel.LoadMarketsData();
                this.loadNetworkData();
            }
        }

        // Handle selection changed on ListBox
        private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ListBox lBox = (ListBox)sender;

            // If selected index is -1 (no selection) do nothing
            if (lBox.SelectedIndex == -1)
                return;

            // Navigate to the new page
            NavigationService.Navigate(new Uri("/CurrencyDetailPage.xaml?selectedItem=" + lBox.SelectedIndex, UriKind.Relative));

            // Reset selected index to -1 (no selection)
            lBox.SelectedIndex = -1;
        }

        /// <summary>
        /// Loads the data shown in the "Network info" control
        /// </summary>
        public void loadNetworkData()
        {
            this.NetworkInfoListbox.Items.Clear();
            this.NetworkStatusProgressBar.Visibility = Visibility.Visible;

            BlockChainDataConnector dc = new BlockChainDataConnector();
            dc.GetUserSelectedData(NetworkStatusChartsDataDownloaded);
        }

        /// <summary>
        /// Callback for the Hash Rate downloaded method
        /// </summary>
        /// <param name="data"></param>
        private void NetworkStatusChartsDataDownloaded(Collection<BlockChainChartItem> ChartsData)
        {
            App.ChartsAllData = ChartsData;

            if (ChartsData.Count > 0)
            {
                foreach (BlockChainChartItem ChartItem in ChartsData)
                {
                    //Create text block with the chart title
                    TextBlock titleBlock = new TextBlock() { HorizontalAlignment = System.Windows.HorizontalAlignment.Center, Margin = new Thickness(0, 0, 0, 0), Text = ChartItem.ChartTitle, TextWrapping = TextWrapping.Wrap, Foreground = new SolidColorBrush(ColorTools.GetColorFromHexa("#FF4D4D4D")), FontSize = 18 };

                    //Create a new RadCartesianChart
                    RadCartesianChart chart = new RadCartesianChart() { Height = 230, Width = 407, Margin = new Thickness(0, -15, 0, 10) };
                    chart.HorizontalAxis = new DateTimeCategoricalAxis() { Foreground = new SolidColorBrush(ColorTools.GetColorFromHexa("#FF4D4D4D")), FontSize = 14, LineThickness = 1, LineStroke = new SolidColorBrush(Colors.Black), Visibility = Visibility.Visible, ShowLabels = false, LabelFitMode = AxisLabelFitMode.Rotate, DateTimeComponent = DateTimeComponent.Day, LastLabelVisibility = AxisLastLabelVisibility.Visible, MajorTickInterval = 40, PlotMode = AxisPlotMode.OnTicks };
                    chart.VerticalAxis = new LinearAxis() { Minimum = ChartItem.Min, Maximum = ChartItem.Max, ShowLabels = true, Foreground = new SolidColorBrush(ColorTools.GetColorFromHexa("#FF4D4D4D")), FontSize = 14, LineStroke = new SolidColorBrush(Colors.Black), LineThickness = 1, Title = ChartItem.YAxistitle, RangeExtendDirection = NumericalAxisRangeExtendDirection.Both };
                    chart.Grid = new CartesianChartGrid() { MajorLinesVisibility = GridLineVisibility.XY, BorderBrush = new SolidColorBrush(Colors.Magenta) };
                    //chart.Grid.MajorXLineStyle = new System.Windows.Style() { TargetType = "Line", Setters = new SetterBaseCollection() };


                    //Create new series for the chart
                    LineSeries lineSeries = new LineSeries();

                    //Set data
                    lineSeries.Stroke = new SolidColorBrush(ColorTools.GetColorFromHexa("#F7931A"));
                    lineSeries.ItemsSource = ChartItem.Data;
                    lineSeries.CategoryBinding = new PropertyNameDataPointBinding() { PropertyName = "ShortDate" };
                    lineSeries.ValueBinding = new PropertyNameDataPointBinding() { PropertyName = "Value" };

                    //Bind the new series to the chart
                    chart.Series.Add(lineSeries);

                    StackPanel Panel = new StackPanel() { Width = 432 };
                    Panel.Children.Add(titleBlock);
                    Panel.Children.Add(chart);

                    //Add the new chart to the GUI
                    this.NetworkInfoListbox.Items.Add(Panel);


                    //Add OnSelectionChanged() event handler here not in XAML
                    this.NetworkInfoListbox.SelectionChanged += this.ListBox_SelectionChanged_1;
                }
            }
            else
            {
                //Create text block with message if no data available
                TextBlock msgBlock = new TextBlock() { HorizontalAlignment = HorizontalAlignment.Center, Margin = new Thickness(20, 120, 0, 0), Text = AppResources.NoItemsAvailable, TextWrapping = TextWrapping.Wrap, Foreground = new SolidColorBrush(ColorTools.GetColorFromHexa("#FF4D4D4D")), FontSize = 22 };

                //Disable the OnSelectionChanged() event
                this.NetworkInfoListbox.SelectionChanged -= this.ListBox_SelectionChanged_1;

                //Add the new item to the GUI
                this.NetworkInfoListbox.Items.Add(msgBlock);
            }

            // Hide the proggressbar
            this.NetworkStatusProgressBar.Visibility = Visibility.Collapsed;
        }

        /// <summary>
        /// Handle the reload button on the App bar
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ApplicationBarIconButton_Click(object sender, EventArgs e)
        {
            App.ViewModel.LoadMarketsData();
            this.loadNetworkData();
        }

        /// <summary>
        /// Navigate to the About page
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ApplicationBarMenuItem_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/AboutPage.xaml", UriKind.Relative));
        }

        /// <summary>
        /// Navigate to the Chart detail page
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ListBox_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
        {
            ListBox lBox = (ListBox)sender;

            // If selected index is -1 (no selection) do nothing
            if (lBox.SelectedIndex == -1)
                return;

            // Navigate to the new page
            NavigationService.Navigate(new Uri("/NetworkStatusChartDetail.xaml?selectedItem=" + lBox.SelectedIndex, UriKind.Relative));

            // Reset selected index to -1 (no selection)
            lBox.SelectedIndex = -1;
        }

        private void ApplicationBarMenuItem_Click_1(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/AppSettingsPage.xaml", UriKind.Relative));
        }

        /**
         * Builds the application Bar with translations
         */
        private void BuildLocalizedApplicationBar()
        {
            ApplicationBar = new ApplicationBar();
            ApplicationBar.ForegroundColor = Colors.Black;
            ApplicationBar.BackgroundColor = ColorTools.GetColorFromHexa("#FFD8D8D8");

            ApplicationBarIconButton appBarIconReload = new ApplicationBarIconButton(new Uri("/Images/appbar.refresh.rest.png", UriKind.Relative));
            appBarIconReload.Text = AppResources.AppBarReload;
            appBarIconReload.Click += this.ApplicationBarIconButton_Click;

            ApplicationBar.Buttons.Add(appBarIconReload);

            ApplicationBarMenuItem appBarItemSettings = new ApplicationBarMenuItem(AppResources.SettingMenuItem);
            appBarItemSettings.Click += this.ApplicationBarMenuItem_Click_1;
            ApplicationBar.MenuItems.Add(appBarItemSettings);

            ApplicationBarMenuItem appBarItemAbout = new ApplicationBarMenuItem(AppResources.AboutMenuItem);
            appBarItemAbout.Click += this.ApplicationBarMenuItem_Click;
            ApplicationBar.MenuItems.Add(appBarItemAbout);
        }
    }

    public class LocalizedStrings
    {
        public LocalizedStrings()
        {
        }

        private static Resources.AppResources localizedResources = new Resources.AppResources();

        public Resources.AppResources LocalizedResources { get { return localizedResources; } }
    }
}